package com.project.platform.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.project.platform.dto.CurrentUserDTO;
import com.project.platform.dto.RetrievePasswordDTO;
import com.project.platform.dto.UpdatePasswordDTO;
import com.project.platform.entity.User;
import com.project.platform.exception.CustomException;
import com.project.platform.mapper.UserMapper;
import com.project.platform.service.UserService;
import com.project.platform.utils.CurrentUserThreadLocal;
import com.project.platform.vo.PageVO;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

  @Resource
  private UserMapper userMapper;

  @Value("resetPassword")
  private String resetPassword;

  /**
   * 获取用户列表
   * */
  @Override
  public List<User> list() {
    return userMapper.list();
  }

  /**
   * 分页获取用户列表
   * */
  @Override
  public PageVO<User> page(Integer pageNum, Integer pageSize, Map<String, Object> query) {
    PageVO<User> page = new PageVO<>();
    page.setList(userMapper.queryPage(pageNum - 1, pageSize, query));
    page.setTotal(userMapper.queryCount(query));
    return page;
  }

  /**
   * 根据用户名查询用户
   * */
  @Override
  public List<User> selectByUsername(String username) {
    return userMapper.selectByUsername(username);
  }

  /**
   * 根据用户名查询用户（精确查询）
   * */
  @Override
  public User selectByUsernameExact(String username) {
    return userMapper.selectByUsernameExact(username);
  }

  /**
   * 登录
   * */
  @Override
  public CurrentUserDTO login(String username, String password) {
    User user = userMapper.selectByUsernameExact(username);
    // 用户不存在
    if(user == null || !user.getPassword().equals(password)) {
      throw new CustomException("用户名或密码错误");
    }
    // 账号被禁用
    if(user.getStatus().equals("禁用")) {
      throw new CustomException("用户已禁用");
    }
    CurrentUserDTO currentUserDTO = new CurrentUserDTO();
    currentUserDTO.setType("USER");
    BeanUtils.copyProperties(user, currentUserDTO);
    return currentUserDTO;
  }

  /**
   * 注册
   * */
  @Override
  public void register(JSONObject data) {
    User user = new User();
    user.setUsername(data.getString("username"));
    user.setPassword(data.getString("password"));
    user.setNickname(data.getString("nickname"));
    user.setAvatarUrl(data.getString("avatarUrl"));
    user.setTel(data.getString("tel"));
    user.setEmail(data.getString("email"));
    // 默认启用
    user.setStatus("启用");
    // 创建时间
    user.setCreateTime(LocalDateTime.now());
    insert(user);
  }

  /**
   * 更新当前用户信息
   * */
  @Override
  public void updateCurrentUserInfo(CurrentUserDTO currentUserDTO) {
    User user = userMapper.selectById(currentUserDTO.getId());
    user.setId(currentUserDTO.getId());
    user.setUsername(currentUserDTO.getUsername());
    user.setNickname(currentUserDTO.getNickname());
    user.setAvatarUrl(currentUserDTO.getAvatarUrl());
    user.setTel(currentUserDTO.getTel());
    user.setEmail(currentUserDTO.getEmail());
    user.setUpdateTime(LocalDateTime.now());
    userMapper.updateById(user);
  }

  /**
   * 修改当前用户密码
   * */
  @Override
  public void updateCurrentUserPassword(UpdatePasswordDTO updatePassword) {
    // 用户主动修改
    User user = userMapper.selectById(CurrentUserThreadLocal.getCurrentUser().getId());
    // 判断旧密码是否正确
    if(user.getPassword().equals(updatePassword.getOldPassword())) {
      throw new CustomException("新密码不能与旧密码相同");
    }
    user.setPassword(updatePassword.getNewPassword());
    userMapper.updateById(user);
  }

  /**
   * 重置密码
   * */
  @Override
  public void resetPassword(Integer id) {
    // 管理员操作
    User user = userMapper.selectById(id);
    user.setPassword(resetPassword);
    userMapper.updateById(user);
  }


  /**
   * 忘记密码
   * */
  @Override
  public void retrievePassword(RetrievePasswordDTO retrievePasswordDTO) {
    User user = userMapper.selectByTel(retrievePasswordDTO.getTel());
    if(user == null) {
      throw new CustomException("手机号不存在");
    }
    // TODO 校验验证码
    user.setPassword(retrievePasswordDTO.getPassword());
    userMapper.updateById(user);
  }

  @Override
  public User selectById(Integer id) {
    return userMapper.selectById(id);
  }

  @Override
  public User selectByTel(String tel) {
    return userMapper.selectByTel(tel);
  }

  /**
   * 插入用户
   * */
  @Override
  public void insert(User user) {
    // 判断用户名是否已存在
    validateHasUserName(user);
    // 传入创建时间
    user.setCreateTime(LocalDateTime.now());
    userMapper.insert(user);
  }

  /**
   * 更新用户
   * */
  @Override
  public void updateById(User user) {
    validateHasUserName(user);
    user.setUpdateTime(LocalDateTime.now());
    userMapper.updateById(user);
  }

  /**
   * 删除用户
   * */
  @Override
  public void removeByIds(List<Integer> ids) {
    userMapper.removeByIds(ids);
  }

  /**
   * 验证用户名是否已存在
   * */
  private void validateHasUserName(User user) {
    // 验证用户名是否已存在
    User user1 = userMapper.selectByUsernameExact(user.getUsername());
    if(user1 != null && user1.getId() != user.getId()) {
      throw new CustomException("用户名已存在");
    }
  }
}
